//import angular core
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';

//import third package
import 'rxjs/add/operator/toPromise';

//import class
import { XiaoRen } from '../domain/xiaoren';

@Injectable()
export class XiaoRenService {
  private api_url = 'http://localhost:3000/xiaoRens';
  private headers = new Headers({ 'Content-Type': 'application/json' });

  constructor(private http: Http) { }

  //select all XiaoRens
  getXiaoRens(): Promise<XiaoRen[]> {
    const url = `${this.api_url}`;
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as XiaoRen[])
      .catch(this.handleError);
  }

  //select XiaoRens by id
  getXiaoRenById(id: number): Promise<XiaoRen> {
    const url = `${this.api_url}/${id}`;
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as XiaoRen)
      .catch(this.handleError);
  }

  //create a XiaoRen
  createXiaoRen(aid:string): Promise<XiaoRen> {
    let xiaoRen = {
      aid: aid
    }
    const url = `${this.api_url}`;
    return this.http
      .post(url, JSON.stringify(xiaoRen), { headers: this.headers })
      .toPromise()
      .then(res => res.json() as XiaoRen)
      .catch(this.handleError);
  }

  //update a XiaoRen
  updateXiaoRen(xiaoRen: XiaoRen): Promise<XiaoRen> {
    const url = `${this.api_url}/${xiaoRen.id}`;
    return this.http
      .put(url, JSON.stringify(xiaoRen), { headers: this.headers })
      .toPromise()
      .then(() => xiaoRen)
      .catch(this.handleError);
  }

  //delete a XiaoRen
  deleteXiaoRen(xiaoRen: XiaoRen): Promise<void> {
    const url = `${this.api_url}/${xiaoRen.id}`;
    return this.http.delete(url, { headers: this.headers })
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

}
